package com.zang.blogz.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zang.blogz.entity.ArticleTag;
import com.zang.blogz.entity.Tag;
import com.zang.blogz.mapper.TagMapper;
import com.zang.blogz.model.output.TagArticleVO;
import com.zang.blogz.model.output.TagViewVO;
import com.zang.blogz.model.output.TagVO;
import com.zang.blogz.model.output.admin.AdminTagVO;
import com.zang.blogz.result.Result;
import com.zang.blogz.service.ArticleTagService;
import com.zang.blogz.service.TagService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author 朵橙i
 * @since 2022-06-17
 */
@Service
public class TagServiceImpl extends ServiceImpl<TagMapper, Tag> implements TagService {

    @Autowired
    private TagMapper tagMapper;

    @Autowired
    private ArticleTagService articleTagService;

    /**
     * 获取标签页所有信息
     *
     * @return
     */
    @Override
    public TagViewVO getTagViewInfo() {

        TagViewVO.TagViewVOBuilder builder = TagViewVO.builder().count(count());
        ArrayList<TagVO> tagVos = new ArrayList<>();
        list().forEach(k -> tagVos.add(TagVO.builder()
                .tagId(k.getId())
                .tagName(k.getTagName()).build()));
        return builder.tagVos(tagVos).build();
    }

    /**
     * 根据id查询标签下所有文章
     *
     * @param tagId
     * @return
     */
    @Override
    public List<TagArticleVO> getTagArticleVoById(Integer tagId) {
        return tagMapper.getTagArticleVoById(tagId);
    }

    @Override
    public List<Tag> getTagListByArticleId(Integer articleId) {

        LambdaQueryWrapper<ArticleTag> lambdaQueryWrapper = new LambdaQueryWrapper<>();

        lambdaQueryWrapper.eq(ArticleTag::getArticleId, articleId);

        List<Integer> list = articleTagService.list(lambdaQueryWrapper).stream().map(ArticleTag::getTagId).collect(Collectors.toList());

        HashSet<Integer> articleTags = new HashSet<>(list);

        return list().stream()
                .filter(tag -> articleTags.contains(tag.getId()))
                .collect(Collectors.toList());
    }

    @Override
    public Tag saveOrEdit(Tag tag) {

        if (tag.getId() == null) {
            save(tag);
        }

        Tag tagById = getById(tag.getId());
        if (tagById == null) {
            save(tag);
        }

        updateById(tag);

        return tag;
    }

    @Override
    public IPage<AdminTagVO> getTagPage(String tagName, Page<Tag> page) {

        LambdaQueryWrapper<Tag> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotBlank(tagName), Tag::getTagName, tagName);

        Page<Tag> tagPage = page(page, queryWrapper);
        Map<Integer, Integer> integerMap = articleTagService.getTagRefCountArticle();

        return tagPage.convert(result -> {
            AdminTagVO vo = new AdminTagVO();
            vo.setCanEdit(Boolean.TRUE);
            vo.setRefCount(integerMap.get(result.getId()));
            vo.setCanDelete(vo.getRefCount() == 0);
            BeanUtil.copyProperties(result, vo);
            return vo;
        });
    }

    @Override
    public Result<String> deleteByTagId(Integer tagId) {

        Tag tag = getById(tagId);
        if (tag == null) {

            throw new RuntimeException(String.format("标签id为{%d}的不存在", tagId));
        }

        long refCount = articleTagService.getArticleCountByTagId(tagId);

        if (refCount > 0) {

            Result.error(String.format("标签id为{%d}还有文章在引用他", tagId));
        }

        removeById(tagId);

        return Result.ok("删除成功");
    }
}
